<template>
  <div class="app-container">
    <el-row :gutter="24">
      <div class="filter-container">
        
        <el-col style="text-align:right;margin-top: -8px;margin-bottom:10px" :span="24">
          <el-button
            size="small"
            font-size="14px"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="handleHookUp"
          >
            新增
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="deleteNotInPayment"
          >
            删除
          </el-button>
        </el-col>
      </div>
    </el-row>
    <div class="grid-content bg-purple" />
    <div
      ref="box"
      class="box"
    >
      
      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <!-- 表格部分 -->
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :data="list"
          :stripe="true"
          :height="tableHeight"
          fit
          style="width: 100%;  margin-left:10px"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
        
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column label="项目分类"  align="center" >
            <template slot-scope="{row}">
              <span>{{ row.proCatCode | proCatCodeFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预算项目"  align="center" >
            <template slot-scope="{row}">
              <span>{{ row.proCode | proCodeFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付方式"  align="center">
            <template slot-scope="{row}">
              <span>{{ row.payTypeCode | payTypeCodeFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="经济分类"   align="center">
            <template slot-scope="{row}">
              <span>{{ row.depBgtEcoCode  }}</span>
            </template>
           </el-table-column>
          <el-table-column label="工资类别"  align="center" >
            <template slot-scope="{row}">
              <span>{{ row.payCategoryCode }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>
    <Drag ref="icon" />
    <!-- 指标挂接 -->
    <el-dialog  v-dialogDrag   title="新增指标过滤规则" :visible.sync="hookUpFormVisible" width="70%" :close-on-click-modal="false">
      <el-form ref="hookUpForm" :model="queryForm" label-position="right" label-width="120px" size="small">
        <el-row style="border: 1px solid #f2f2f2; margin-top: 1%">
          <el-col :span="5.5">
            <el-form-item label="项目分类" prop="proCatCodeList"  style="background-color: #f2f2f2" />
            <el-select v-model="queryForm.proCatCodeList" multiple class="filter-item" clearable placeholder="--请选择--" style="width:100%">
              <el-option v-for="item in proCatLists" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="预算项目"  prop="proCodeList" style="background-color: #f2f2f2" />
            <el-select v-model="queryForm.proCodeList" multiple class="filter-item" clearable placeholder="--请选择--" style="width:100%">
              <el-option v-for="item in proLists" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="支付方式"  prop="payTypeCodeList"  style="background-color: #f2f2f2" />
            <el-select v-model="queryForm.payTypeCodeList" multiple class="filter-item" clearable placeholder="--请选择--" style="width:100%">
              <el-option v-for="item in payTypeLists" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="经济分类"  prop="depBgtEcoCodeList"  style="background-color: #f2f2f2" />
            <el-select ref="selectReport" v-model="depBgtEcoName"  class="filter-item" clearable placeholder="--请选择--" style="width:100%" @clear="clearHandle">
              <el-option :value="queryForm.depBgtEcoCodeList" :label="depBgtEcoName" style="height:200px;overflow: auto;background-color:#fff">
                <el-tree
                  :data="depBgtEcoLists"
                  :accordion="true"
                  :highlight-current="true"
                  :props="defaultProps"
                  :node-key="defaultProps.id"
                  :default-expanded-keys="defaultExpandedKey"
                  @node-click="handleNodeClick"
                />
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="工资类别" prop="payCategoryCodeList" style="background-color: #f2f2f2" />
            <el-select ref="selectPayReport" v-model="payCategoryName" class="filter-item" clearable  style="width:100%"  @clear="clearPayHandle">
              <el-option :value="queryForm.payCategoryCodeList" :label="payCategoryName" style="height:200px;overflow: auto;background-color:#fff">
                <el-tree
                  :data="payCategoryLists"
                  :accordion="true"
                  :highlight-current="true"
                  :props="defaultProps"
                  :node-key="defaultProps.id"
                  :default-expanded-keys="defaultPayExpandedKey"
                  @node-click="handlePayNodeClick"
                />
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="text-align: center; margin-top:2%">
            <el-button type="primary" :loading="saveLoading" @click="handlesaveNotInPayment">
              确定
            </el-button>
            <el-button @click="hookUpFormVisible = false">
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { queryNotInPaymentPage, saveNotInPayment,
  deleteNotInPayment } from '@/api/salaryConfigManage/notInPayment'
import { getPayType, getProCat, getPro, getDepBgtEco, getPayCategory } from '@/api/baseInfo'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  name: 'Index',
  components: { Pagination, tableEmpty, AgencyTree, Drag },
  filters: {
    proCatCodeFilter(type,that) {//项目分类
       const  proCatCode = that.proCatLists
       if(type!=null)
       {
         let re=''
        let arry= type.split(',')
      for (let i=0;i<arry.length;i++) {
        for (const item in  proCatCode) {
          if ( proCatCode[item].code === arry[i]) {
            if(i!=0){
              re+=','
            }
           re+=proCatCode[item].name
          }
        }
      }
       return re
    }
      return ''
    },
    proCodeFilter(type,that) {//预算项目
    
     const  proCode = that.proLists
       if(type!=null)
       {
         let re=''
        let arry= type.split(',')
      for (let i=0;i<arry.length;i++) {
        for (const item in  proCode) {
          if ( proCode[item].code === arry[i]) {
            if(i!=0){
              re+=','
            }
           re+=proCode[item].name
          }
        }
      }
       return re
    }
      return ''
    },
    payTypeCodeFilter(type,that) {//支付方式
      const  proCode = that.payTypeLists
       if(type!=null)
       {
         let re=''
        let arry= type.split(',')
      for (let i=0;i<arry.length;i++) {
        for (const item in  proCode) {
          if ( proCode[item].code === arry[i]) {
            if(i!=0){
              re+=','
            }
           re+=proCode[item].name
          }
        }
      }
       return re
    }
      return ''
    },
    depBgtEcoCodeFilter(type,that) { //经济分类
      const  proCode = that.depBgtEcoLists
       if(type!=null)
       {
         let re=''
        let arry= type.split(',')
      for (let i=0;i<arry.length;i++) {
        for (const item in  proCode) {
          if ( proCode[item].code === arry[i]) {
            if(i!=0){
              re+=','
            }
           re+=proCode[item].label
          }
        }
      }
       return re
    }
      return ''
    },
    payCategoryCodeFilter(type,that) {//工资类别
      const  proCode = that.payCategoryLists
       if(type!=null)
       {
         let re=''
        let arry= type.split(',')
      for (let i=0;i<arry.length;i++) {
        for (const item in  proCode) {
          if ( proCode[item].code === arry[i]) {
            if(i!=0){
              re+=','
            }
           re+=proCode[item].name
          }
        }
      }
       return re
    }
      return ''
    }
    
  },
  data() {
    return {
      treeHeight: null,
      isActive: true,
      Show: false,
      treeShow: false,
      treeData: '',
      tableHeight: null,
      that: this,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 200,
        agencyId: '0'
      },
      payTypeLists: [], // 支付方式
      proCatLists: [], // 项目分类
      proLists: [], // 预算项目
      depBgtEcoLists: [], // 政府经济分类
      payCategoryLists: [], // 工资类别
      hookUpFormVisible: false,
      indexLoading: false,
      usingList: [{ 'code': '1', 'name': '启用' }, { 'code': '0', 'name': '停用' }],
      indexList: [],
      indexTotal: 0,
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      defaultExpandedKey: [],
      defaultPayExpandedKey: [11],
      formData: {
        offset: 1,
        limit: 200
      },
      queryForm:{
        payTypeCode: '',
        proCatCode: '',
        proCode: '',
        depBgtEcoCode: '',
        payCategoryCode: '',
        payTypeCodeList: [],
        proCatCodeList:[],
        proCodeList:[],
        depBgtEcoCodeList: [],
        payCategoryCodeList: []
      },
      depBgtEcoName: '',
      payCategoryName: '',
      hookUpQuery: {
        salaryId: '',
        personType: '',
        agencyId: ''
      },
      hookUpLoading: false,
      saveLoading: false,
      selection: [],
      hookUpList: [],
      checkSumIdList: []
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.getList()
    this.initBaseInfo()
  },
  mounted() {
    this.getTbHeight()
    this.dragController()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },

  methods: {
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    getFirstAuthAgencyData(data) {
      this.treeData = data
      this.handleTree(data)
    },
    handleTreeQuery(data) {
      this.treeData = data
      this.handleTree(data)
    },
    handleTree(data) {
      if (data.isleaf === '1') {
        this.listQuery.agencyId = data.id
        this.getList()
      }
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 228
      this.treeHeight = window.innerHeight - 228
    },
    getList() {
      this.listLoading = true
      queryNotInPaymentPage(this.listQuery).then(response => {
      
        this.list = response.data.rows // 打开求和，就注销这一句
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleQuery() {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
    },
    // 指标挂接
    handleHookUp() {
      
      this.indexList = []
      this.indexTotal = 0
      this.hookUpList = []
      this.checkSumIdList = []
      this.hookUpFormVisible = true

    },
    deleteNotInPayment(){
      this.selection = []
      this.selection = this.$refs.singalTable.selection
      if (this.selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择要删除的规则',
          type: 'warning',
          duration: 4000
        })
        return
      }
      deleteNotInPayment(this.selection[0]).then((response) => {
        this.$message({
                message: '删除成功',
                type: 'success',
                showClose: true,
                duration: 4000
              })
        this.handleQuery()
      })
    },
    handleAllChecked(rows) { // 全选事件
      const _that = this
      if (rows.length === 0) {
        const rows2 = _that.indexList

        rows2.forEach(function(item) {
          _that.handleDeleteClick(item) // 删除
        })
      }
      rows.forEach(function(item) {
        _that.handleIndexChecked(rows, item)
      })
    },
    // 预算指标表点击复选框事件
    handleIndexChecked(rows, row) {
      // 如果rows有值，则进行判断，如果没有，直接删除row数据
      if (rows.length > 0) {
        // 如果rows里不包含当前选中的行数据，则为删除数据；否则为增加数据
        if (rows.indexOf(row) < 0) {
          if (this.hookUpList.length > 0) {
            for (const index in this.hookUpList) {
              if (this.hookUpList[index]['bgtId'] === row.bgtId) {
                this.hookUpList.splice(index, 1)
              }
            }
          }
          const checkedIndex = this.checkSumIdList.indexOf(row.bgtId)
          this.checkSumIdList.splice(checkedIndex, 1)
        } else {
          // 判断已挂接的是否存在选中的数据，如果不存在则添加
          let flag = false
          this.hookUpList.forEach(item => {
            if (item.bgtId === row.bgtId) {
              flag = true
            }
          })
          if (!flag) {
            this.hookUpList.push(row)
            this.checkSumIdList.push(row.bgtId)
          }
        }
      } else {
        const index = this.hookUpList.indexOf(row)
        this.hookUpList.splice(index, 1)
        const checkedIndex = this.checkSumIdList.indexOf(row.bgtId)
        this.checkSumIdList.splice(checkedIndex, 1)
      }
    },
    // 保存
    handlesaveNotInPayment() {
      this.saveLoading = true
      saveNotInPayment(this.queryForm).then((response) => {
        this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.hookUpFormVisible = false
        this.handleQuery()
        this.clearPayHandle() 
        this.clearHandle() 
      }).catch(() => {
        this.saveLoading = false
      })
    },
    // 树点击
    handleNodeClick(data) {
      if (data.isleaf === '1') {
        this.queryForm.depBgtEcoCodeList.push(data.code)
        this.depBgtEcoName = data.label
        this.$refs.selectReport.blur()
      }
    },
    // 清除下拉树选中
    clearHandle() {
      this.depBgtEcoName = ''
      this.queryForm.depBgtEcoCode = ''
      this.queryForm.depBgtEcoCodeList=[]
      this.defaultExpandedKey = []
    },
    // 树点击
    handlePayNodeClick(data) {
      // if (data.code === '11') {
        if (data.isleaf === '1') {
        this.queryForm.payCategoryCodeList.push(data.code)
        this.payCategoryName = data.label
        this.$refs.selectPayReport.blur()
        }
      // }
    },
    // 清除工资类别下拉树
    clearPayHandle() {
      this.payCategoryName = ''
      this.queryForm.payCategoryCode = ''
      this.defaultPayExpandedKey = []
    },
    // 初始化基础数据
    initBaseInfo() {
      // 支付方式
      getPayType().then((response) => {
        this.payTypeLists = Object.assign({}, response.data)
      })
      // 项目分类
      getProCat().then((response) => {
        this.proCatLists = Object.assign({}, response.data)
      })
      // 预算项目
      getPro().then((response) => {
        this.proLists = Object.assign({}, response.data)
      })
      // 政府经济分类
      getDepBgtEco().then((response) => {
        this.depBgtEcoLists = response.data
      })
      // 工资类别
      getPayCategory().then((response) => {
        this.payCategoryLists = response.data
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.cell-input{
  width: 80%;
}
::v-deep .indexTable {
  .el-table__header-wrapper {
     .el-checkbox {
      display: none;
    }
  }

}
::v-deep.hookUpTable {
  .el-input{
    width: auto !important;
  }
}
::v-deep.el-select-dropdown__item.selected {
  font-weight: normal;
}
</style>
